package com.yckj.activechicken.common.utils.file;

import com.yckj.activechicken.common.utils.DateUtils;
import com.yckj.activechicken.common.utils.StringUtils;
import com.yckj.activechicken.framework.config.ProjectConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件处理工具类
 *
 * @author zhoujy
 */
public class FileUtils {
    private static final Logger log = LoggerFactory.getLogger(FileUtils.class);

    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

    /**
     * 存储单个文件
     * @param multipartFile 上传文件流
     * @param filePath 存储的指定目录
     * @return
     */
    public static Map<String,String> uploadFile(MultipartFile multipartFile,String filePath){

        Map<String,String> outMap = new HashMap<>(2);
        if(!multipartFile.isEmpty() && StringUtils.isNotEmpty(filePath)){
            //获取存放文件的目录
            String uploadPath = ProjectConfig.getProfile()+filePath;
            //创建文件对象
            File upload = new File(uploadPath);
            //如果该目录在磁盘下不存在，则创建
            if(!upload.exists()){
                upload.mkdirs();
            }

            //文件名称：时间戳,上传文件名
            String fileName = DateUtils.dateTimeNow() + "," + multipartFile.getOriginalFilename();

            File file = new File(upload,fileName);
            try {
                multipartFile.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
                log.debug(fileName + "创建失败！");
                outMap.put("result","false");
                outMap.put("message",fileName + "创建失败！");
                return outMap;
            }

            outMap.put("result","true");
            outMap.put("localFileName",fileName);
            outMap.put("fileName",multipartFile.getOriginalFilename());
            outMap.put("uploadPath",filePath + "/" + fileName);
            outMap.put("mimeType",getExtensionName(multipartFile.getOriginalFilename()));
            return outMap;
        }else{
            outMap.put("result","false");
            outMap.put("message","上传文件不存在或存储路径不存在！");
            return outMap;
        }
    }

    /**
     * 处理多文件上传操作
     * @param multipartFileList
     * @param filePath
     * @return
     */
    public static List<Map<String,String>> uploadFileList(MultipartFile[] multipartFileList, String filePath){
        List<Map<String,String>> outList = new ArrayList<>();
        if(StringUtils.isNotEmpty(multipartFileList) && StringUtils.isNotEmpty(filePath)){
            for(MultipartFile multipartFile : multipartFileList){
                Map<String,String> outMap = uploadFile(multipartFile,filePath);
                outList.add(outMap);
            }
        }
        return outList;
    }

    /**
     * 输出指定文件的byte数组，多用于文件下载
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

    /**
     * 获取文件扩展名
     * @param filename
     * @return
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }
}
